package com.bbs.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Controller
public class AlipayController {

    private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);

    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.privateKey}")
    private String privateKey;

    @Value("${alipay.publicKey}")
    private String alipayPublicKey;

    @Value("${alipay.notifyUrl}")
    private String notifyUrl;

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    @GetMapping("/alipay")
    public String Alipay() {
        return "user/alipay";
    }

    @PostMapping("/create")
    public void create(HttpServletResponse response) throws IOException {

        // 生成随机订单ID
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        // 固定金额和标题
        String money = "15";
        String title = "开通会员";

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi-sandbox.dl.alipaydev.com/gateway.do", appId, privateKey, "json", "UTF-8", alipayPublicKey, "RSA2");
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(returnUrl);
        alipayRequest.setNotifyUrl(notifyUrl);

        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" + id + "\"," +
                "    \"total_amount\":\"" + money + "\"," +
                "    \"subject\":\"" + title + "\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                "}");

        try {
            logger.info("发送请求到支付宝: {}", alipayRequest.getBizContent());
            String form = alipayClient.pageExecute(alipayRequest).getBody();
            logger.info("支付宝返回的表单: {}", form);

            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(form);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            logger.error("调用支付宝接口异常", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "调用支付宝接口异常");
        }
    }
}
